﻿/******************************************************************************
 *  All Rights Reserved , Copyright (C) 2012 , EricHu. 
 *  作    者： EricHu
 *  创建时间： 2012-4-17 14:29:02
 ******************************************************************************/
using System;
using System.Data;

namespace RDIFramework.ServiceAdapter
{
    using RDIFramework.BusinessEntity;
    using RDIFramework.Utilities;
  

    /// <summary>
    /// PiPermissionItemManager
    /// 操作权限项定义
    ///
    /// 修改纪录
    ///
    ///		2012-03-02 版本：1.0 EricHu 创建主键。
    ///
    /// 版本：1.0
    ///
    /// <author>
    ///		<name>EricHu</name>
    ///		<date>2012-03-02</date>
    /// </author>
    /// </summary>
    public partial class PiPermissionItemManager : DbCommonManager, IDbCommonManager
    {
        private static readonly object PermissionItemLock = new object();

        /// <summary>
        /// 构造函数
        /// </summary>
        public PiPermissionItemManager()
        {
            if (base.dbProvider == null)
            {
                base.dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType, SystemInfo.RDIFrameworkDbConection);
            }
            base.CurrentTableName = PiPermissionItemTable.TableName;
        }

        /// <summary>
        /// 构造函数
        /// <param name="tableName">指定表名</param>
        /// </summary>
        public PiPermissionItemManager(string tableName)
        {
            base.CurrentTableName = tableName;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbProvider">数据库连接</param>
        public PiPermissionItemManager(IDbProvider dbProvider)
            : this()
        {
            DBProvider = dbProvider;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        public PiPermissionItemManager(UserInfo userInfo)
            : this()
        {
            UserInfo = userInfo;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbProvider">数据库连接</param>
        /// <param name="userInfo">用户信息</param>
        public PiPermissionItemManager(IDbProvider dbProvider, UserInfo userInfo)
            : this(dbProvider)
        {
            UserInfo = userInfo;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbProvider">数据库连接</param>
        /// <param name="userInfo">用户信息</param>
        /// <param name="tableName">指定表名</param>
        public PiPermissionItemManager(IDbProvider dbProvider, UserInfo userInfo, string tableName)
            : this(dbProvider, userInfo)
        {
            base.CurrentTableName = tableName;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="permissionItemEntity">实体</param>
        /// <returns>主键</returns>
        public string Add(PiPermissionItemEntity permissionItemEntity)
        {
            return this.AddEntity(permissionItemEntity);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="permissionItemEntity">实体</param>
        /// <param name="identity">自增量方式</param>
        /// <param name="returnId">返回主鍵</param>
        /// <returns>主键</returns>
        public string Add(PiPermissionItemEntity permissionItemEntity, bool identity, bool returnId)
        {
            this.Identity = identity;
            this.ReturnId = returnId;
            return this.AddEntity(permissionItemEntity);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="permissionItemEntity">实体</param>
        public int Update(PiPermissionItemEntity permissionItemEntity)
        {
            return this.UpdateEntity(permissionItemEntity);
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id">主键</param>
        public PiPermissionItemEntity GetEntity(int id)
        {
            return GetEntity(id.ToString());
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id">主键</param>
        public PiPermissionItemEntity GetEntity(string id)
        {
            PiPermissionItemEntity permissionItemEntity = new PiPermissionItemEntity(this.GetDT(PiPermissionItemTable.FieldId, id));
            return permissionItemEntity;
        }

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="permissionItemEntity">实体</param>
        public string AddEntity(PiPermissionItemEntity permissionItemEntity)
        {
            string sequence = string.Empty;
            if (permissionItemEntity.SortCode == 0 || permissionItemEntity.SortCode == null)
            {
                CiSequenceManager sequenceManager = new CiSequenceManager(DBProvider, this.Identity);
                sequence = sequenceManager.GetSequence(this.CurrentTableName);
                permissionItemEntity.SortCode = int.Parse(sequence);
            }
            SQLBuilder sqlBuilder = new SQLBuilder(DBProvider, this.Identity, this.ReturnId);
            sqlBuilder.BeginInsert(PiPermissionItemTable.TableName, PiPermissionItemTable.FieldId);
            if (!this.Identity)
            {
                sqlBuilder.SetValue(PiPermissionItemTable.FieldId, permissionItemEntity.Id);
            }
            else
            {
                if (!this.ReturnId && (DBProvider.CurrentDbType == CurrentDbType.Oracle || DBProvider.CurrentDbType == CurrentDbType.DB2))
                {
                    if (DBProvider.CurrentDbType == CurrentDbType.Oracle)
                    {
                        sqlBuilder.SetFormula(PiPermissionItemTable.FieldId, "SEQ_" + this.CurrentTableName.ToUpper() + ".NEXTVAL ");
                    }
                    if (DBProvider.CurrentDbType == CurrentDbType.DB2)
                    {
                        sqlBuilder.SetFormula(PiPermissionItemTable.FieldId, "NEXT VALUE FOR SEQ_" + this.CurrentTableName.ToUpper());
                    }
                }
                else
                {
                    if (this.Identity && (DBProvider.CurrentDbType == CurrentDbType.Oracle || DBProvider.CurrentDbType == CurrentDbType.DB2))
                    {
                        if (permissionItemEntity.Id == null)
                        {
                            if (string.IsNullOrEmpty(sequence))
                            {
                                CiSequenceManager sequenceManager = new CiSequenceManager(DBProvider, this.Identity);
                                sequence = sequenceManager.GetSequence(this.CurrentTableName);
                            }
                            permissionItemEntity.Id = int.Parse(sequence);
                        }
                        sqlBuilder.SetValue(PiPermissionItemTable.FieldId, permissionItemEntity.Id);
                    }
                }
            }
            this.SetEntity(sqlBuilder, permissionItemEntity);
            if (UserInfo != null)
            {
                sqlBuilder.SetValue(PiPermissionItemTable.FieldCreateUserId, UserInfo.Id);
                sqlBuilder.SetValue(PiPermissionItemTable.FieldCreateBy, UserInfo.RealName);
            }
            sqlBuilder.SetDBNow(PiPermissionItemTable.FieldCreateOn);
            if (UserInfo != null)
            {
                sqlBuilder.SetValue(PiPermissionItemTable.FieldModifyUserId, UserInfo.Id);
                sqlBuilder.SetValue(PiPermissionItemTable.FieldModifiedBy, UserInfo.RealName);
            }
            sqlBuilder.SetDBNow(PiPermissionItemTable.FieldModifiedOn);
            if (DBProvider.CurrentDbType == CurrentDbType.SqlServer && this.Identity)
            {
                sequence = sqlBuilder.EndInsert().ToString();
            }
            else
            {
                sqlBuilder.EndInsert();
            }
            return sequence;
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="permissionItemEntity">实体</param>
        public int UpdateEntity(PiPermissionItemEntity permissionItemEntity)
        {
            SQLBuilder sqlBuilder = new SQLBuilder(DBProvider);
            sqlBuilder.BeginUpdate(PiPermissionItemTable.TableName);
            this.SetEntity(sqlBuilder, permissionItemEntity);
            if (UserInfo != null)
            {
                sqlBuilder.SetValue(PiPermissionItemTable.FieldModifyUserId, UserInfo.Id);
                sqlBuilder.SetValue(PiPermissionItemTable.FieldModifiedBy, UserInfo.RealName);
            }
            sqlBuilder.SetDBNow(PiPermissionItemTable.FieldModifiedOn);
            sqlBuilder.SetWhere(PiPermissionItemTable.FieldId, permissionItemEntity.Id);
            return sqlBuilder.EndUpdate();
        }

        /// <summary>
        /// 设置实体
        /// </summary>
        /// <param name="permissionItemEntity">实体</param>
        private void SetEntity(SQLBuilder sqlBuilder, PiPermissionItemEntity permissionItemEntity)
        {
            sqlBuilder.SetValue(PiPermissionItemTable.FieldParentId, permissionItemEntity.ParentId);
            sqlBuilder.SetValue(PiPermissionItemTable.FieldCode, permissionItemEntity.Code);
            sqlBuilder.SetValue(PiPermissionItemTable.FieldFullName, permissionItemEntity.FullName);
            sqlBuilder.SetValue(PiPermissionItemTable.FieldCategoryCode, permissionItemEntity.CategoryCode);
            sqlBuilder.SetValue(PiPermissionItemTable.FieldIsScope, permissionItemEntity.IsScope);
            sqlBuilder.SetValue(PiPermissionItemTable.FieldIsPublic, permissionItemEntity.IsPublic);
            sqlBuilder.SetValue(PiPermissionItemTable.FieldAllowEdit, permissionItemEntity.AllowEdit);
            sqlBuilder.SetValue(PiPermissionItemTable.FieldAllowDelete, permissionItemEntity.AllowDelete);
            sqlBuilder.SetValue(PiPermissionItemTable.FieldLastCall, permissionItemEntity.LastCall);
            sqlBuilder.SetValue(PiPermissionItemTable.FieldEnabled, permissionItemEntity.Enabled);
            sqlBuilder.SetValue(PiPermissionItemTable.FieldDeleteMark, permissionItemEntity.DeleteMark);
            sqlBuilder.SetValue(PiPermissionItemTable.FieldSortCode, permissionItemEntity.SortCode);
            sqlBuilder.SetValue(PiPermissionItemTable.FieldDescription, permissionItemEntity.Description);
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>影响行数</returns>
        public int Delete(int id)
        {
            return this.Delete(PiPermissionItemTable.FieldId, id);
        }

        /// <summary>
        /// 获取一个操作权限的主键
        /// 若不存在就自动增加一个
        /// </summary>
        /// <param name="permissionItemCode">操作权限编号</param>
        /// <param name="permissionItemName">操作权限名称</param>
        /// <returns>主键</returns>
        public string GetIdByAdd(string permissionItemCode, string permissionItemName = null)
        {
            // 判断当前判断的权限是否存在，否则很容易出现前台设置了权限，后台没此项权限
            // 需要自动的能把前台判断过的权限，都记录到后台来

            string[] names = new string[] { PiPermissionItemTable.FieldDeleteMark, PiPermissionItemTable.FieldEnabled, PiPermissionItemTable.FieldCode };
            object[] values = new object[] { 0, 1, permissionItemCode };

            PiPermissionItemEntity permissionItemEntity = new PiPermissionItemEntity();
            permissionItemEntity = new PiPermissionItemEntity(this.GetDT(names, values, PiPermissionItemTable.FieldId));

            string permissionItemId = string.Empty;
            if (permissionItemEntity != null)
            {
                permissionItemId = permissionItemEntity.Id.ToString();
            }

            // 若是在调试阶段、有没在的权限被判断了，那就自动加入这个权限，不用人工加入权限了，工作效率会提高很多，
            // 哪些权限是否有被调用什么的，还可以进行一些诊断
            #if (DEBUG)
            if (String.IsNullOrEmpty(permissionItemId))
            {
                // 这里需要进行一次加锁，方式并发冲突发生
                lock (PermissionItemLock)
                {
                    permissionItemEntity.Code = permissionItemCode;
                    if (string.IsNullOrEmpty(permissionItemName))
                    {
                        permissionItemEntity.FullName = permissionItemCode;
                    }
                    else
                    {
                        permissionItemEntity.FullName = permissionItemName;
                    }
                    permissionItemEntity.ParentId = null;
                    permissionItemEntity.IsScope = 0;
                    permissionItemEntity.AllowDelete = 1;
                    permissionItemEntity.AllowEdit = 1;
                    permissionItemEntity.Enabled = 1;
                    // 这里是防止主键重复？
                    // permissionEntity.ID = BusinessLogic.NewGuid();
                    permissionItemId = this.AddEntity(permissionItemEntity);
                }
            }
            else
            {
                // 更新最后一次访问日期，设置为当前服务器日期
                SQLBuilder sqlBuilder = new SQLBuilder(DBProvider);
                sqlBuilder.BeginUpdate(PiPermissionItemTable.TableName);
                sqlBuilder.SetDBNow(PiPermissionItemTable.FieldLastCall);
                sqlBuilder.SetWhere(PiPermissionItemTable.FieldId, permissionItemId);
                sqlBuilder.EndUpdate();
            }
            #endif

            return permissionItemId;
        }


        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="code">编号</param>
        /// <param name="fullName">名称</param>
        /// <param name="statusCode">返回状态码</param>
        /// <returns>主键</returns>
        public string AddByDetail(string code, string fullName, out string statusCode)
        {
            PiPermissionItemEntity permissionItemEntity = new PiPermissionItemEntity();
            permissionItemEntity.Code = code;
            permissionItemEntity.FullName = fullName;
            return this.Add(permissionItemEntity, out statusCode);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="permissionEntity">实体</param>
        /// <param name="statusCode">返回状态码</param>
        /// <returns>主键</returns>
        public string Add(PiPermissionItemEntity permissionItemEntity, out string statusCode)
        {
            string returnValue = string.Empty;
            // 检查编号是否重复
            if (this.Exists(PiPermissionItemTable.FieldDeleteMark, 0, PiPermissionItemTable.FieldCode, permissionItemEntity.Code))
            {
                // 编号已重复
                statusCode = StatusCode.ErrorCodeExist.ToString();
            }
            else
            {
                returnValue = this.AddEntity(permissionItemEntity);
                // 运行成功
                statusCode = StatusCode.OKAdd.ToString();
            }
            return returnValue;
        }

        /// <summary>
        /// 获取一个
        /// </summary>
        /// <param name="code">编号</param>
        /// <param name="statusCode">返回状态码</param>
        /// <returns>数据表</returns>
        public DataTable GetDTByCode(string code)
        {
            return this.GetDT(PiPermissionItemTable.FieldCode, code);
        }

        /// <summary>
        /// 获取一个
        /// </summary>
        /// <param name="code">编号</param>
        /// <param name="permissionEntity">实体</param>
        /// <returns>数据表</returns>
        public DataTable GetByCode(string code, PiPermissionItemEntity permissionItemEntity)
        {
            DataTable dataTable = this.GetDT(PiPermissionItemTable.FieldCode, code);
            permissionItemEntity.GetFrom(dataTable);
            return dataTable;
        }

        /// <summary>
        /// 更新一个
        /// </summary>
        /// <param name="permissionEntity">实体</param>
        /// <param name="statusCode">返回状态码</param>
        /// <returns>影响行数</returns>
        public int Update(PiPermissionItemEntity permissionItemEntity, out string statusCode)
        {
            int returnValue = 0;
            // 检查是否已被其他人修改            
            //if (DbLogic.IsModifed(DBProvider, PiPermissionTable.TableName, permissionEntity.Id, permissionEntity.ModifiedUserId, permissionEntity.ModifiedOn))
            //{
            //    // 数据已经被修改
            //    statusCode = StatusCode.ErrorChanged.ToString();
            //}
            //else
            //{
            // 检查编号是否重复
            if (this.Exists(PiPermissionItemTable.FieldDeleteMark, 0, PiPermissionItemTable.FieldCode, permissionItemEntity.Code, permissionItemEntity.Id))
            {
                // 文件夹名已重复
                statusCode = StatusCode.ErrorCodeExist.ToString();
            }
            else
            {
                // 进行更新操作
                returnValue = this.UpdateEntity(permissionItemEntity);
                if (returnValue == 1)
                {
                    statusCode = StatusCode.OKUpdate.ToString();
                }
                else
                {
                    // 数据可能被删除
                    statusCode = StatusCode.ErrorDeleted.ToString();
                }
            }
            //}
            return returnValue;
        }

        /// <summary>
        /// 删除一个
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>影响行数</returns>
        public int Delete(string id)
        {
            // 删除关联数据
            int returnValue = 0;
            returnValue = this.DeleteEntity(id);
            /*
            BUBaseModulePermission ModulePermission = new BUBaseModulePermission(OleDBProvider, userInfo);
            // 是否强制删除关联数据
            if (force)
            {
                returnValue = ModulePermission.Delete(BUBaseModulePermission.FieldPermissionId, id);
                returnValue += this.DeleteEntity(id);
                this.ReturnStatusCode = StatusCode.OKDelete;
            }
            else
            {
                // 检查是否有关联数据存在
                if (ModulePermission.Exists(BUBaseModulePermission.FieldPermissionId, id))
                {
                    // 已有关联数据
                    this.ReturnStatusCode = StatusCode.ErrorDataRelated;
                }
                else
                {
                    returnValue = this.DeleteEntity(id);
                    this.ReturnStatusCode = StatusCode.OKDelete;
                }
            }            
            */
            return returnValue;
        }


        /// <summary>
        /// 获得用户授权范围
        /// </summary>
        /// <param name="staffId">员工主键</param>
        /// <returns>数据表</returns>
        public DataTable GetDTByUser(string userId, string permissionItemCode)
        {
            DataTable returnValue = new DataTable(this.CurrentTableName);
            string[] names = null;
            object[] values = null;

            // 这里需要判断,是系统权限？
            bool isRole = false;
            PiUserRoleManager userRoleManager = new PiUserRoleManager(this.DBProvider, this.UserInfo);
            // 用户管理员
            isRole = userRoleManager.UserInRole(userId, "UserAdmin");
            if (isRole)
            {
                names = new string[] { PiPermissionItemTable.FieldCategoryCode, PiPermissionItemTable.FieldDeleteMark, PiPermissionItemTable.FieldEnabled };
                values = new object[] { "System", 0, 1 };
                returnValue = this.GetDT(names, values, PiPermissionItemTable.FieldSortCode);
                returnValue.TableName = this.CurrentTableName;
                return returnValue;
            }

            // 这里需要判断,是业务权限？
            isRole = userRoleManager.UserInRole(userId, "Admin");
            if (isRole)
            {
                names = new string[] { PiPermissionItemTable.FieldCategoryCode, PiPermissionItemTable.FieldDeleteMark, PiPermissionItemTable.FieldEnabled };
                values = new object[] { "Application", 0, 1 };
                returnValue = this.GetDT(names, values, PiPermissionItemTable.FieldSortCode);
                returnValue.TableName = this.CurrentTableName;
                return returnValue;
            }

            PiPermissionScopeManager permissionScopeManager = new PiPermissionScopeManager(DBProvider, UserInfo);
            string[] permissionItemIds = permissionScopeManager.GetTreeResourceScopeIds(userId, PiPermissionItemTable.TableName, permissionItemCode, true);
            // 有效的，未被删除的
            names = new string[] { PiPermissionItemTable.FieldId, PiPermissionItemTable.FieldDeleteMark, PiPermissionItemTable.FieldEnabled };
            values = new object[] { permissionItemIds, 0, 1 };
            returnValue = this.GetDT(names, values, PiPermissionItemTable.FieldSortCode);
            returnValue.TableName = this.CurrentTableName;
            return returnValue;
        }


        /// <summary>
        /// 批量保存
        /// </summary>
        /// <param name="dataTable">数据表</param>
        /// <returns>影响行数</returns>
        public override int BatchSave(DataTable dataTable)
        {
            int returnValue = 0;
            PiPermissionItemEntity permissionItemEntity = new PiPermissionItemEntity();
            foreach (DataRow dataRow in dataTable.Rows)
            {
                // 删除状态
                if (dataRow.RowState == DataRowState.Deleted)
                {
                    string id = dataRow[PiPermissionItemTable.FieldId, DataRowVersion.Original].ToString();
                    if (id.Length > 0)
                    {
                        if (dataRow[PiPermissionItemTable.FieldAllowDelete, DataRowVersion.Original].ToString().Equals("1"))
                        {
                            returnValue += this.DeleteEntity(id);
                        }
                    }
                }
                // 被修改过
                if (dataRow.RowState == DataRowState.Modified)
                {
                    string id = dataRow[PiPermissionItemTable.FieldId, DataRowVersion.Original].ToString();
                    if (id.Length > 0)
                    {
                        permissionItemEntity.GetFrom(dataRow);
                        // 判断是否允许编辑
                        if (permissionItemEntity.AllowEdit == 1)
                        {
                            returnValue += this.UpdateEntity(permissionItemEntity);
                        }
                        else
                        {
                            // 不允许编辑，但是排序还是允许的
                            returnValue += this.SetProperty(PiPermissionItemTable.FieldId, id, PiPermissionItemTable.FieldSortCode, permissionItemEntity.SortCode);
                        }
                    }
                }
                // 添加状态
                if (dataRow.RowState == DataRowState.Added)
                {
                    permissionItemEntity.GetFrom(dataRow);
                    returnValue += this.AddEntity(permissionItemEntity).Length > 0 ? 1 : 0;
                }
                if (dataRow.RowState == DataRowState.Unchanged)
                {
                    continue;
                }
                if (dataRow.RowState == DataRowState.Detached)
                {
                    continue;
                }
            }
            return returnValue;
        }

        /// <summary>
        /// 移动
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="parentId">父级主键</param>
        /// <returns>影响行数</returns>
        public int MoveTo(string id, string parentId)
        {
            return this.SetProperty(id, PiOrganizeTable.FieldParentId, parentId);
        }
    }
}
